﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using ImageTools.IO.Gif;
using System.IO;
using ImageTools.IO.Jpeg;
using System.Diagnostics;

namespace Code4WP7SDK.Converter
{
    public class ImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            BitmapImage bitmapimage = new BitmapImage();
            if (value != null)
            {
                string imageUrl = value.ToString();
                //Debug.WriteLine("Url:" + imageUrl);
                WebClient ws = new WebClient();
                ws.OpenReadCompleted += (s, e) =>
                {
                    if (e.Error == null)
                    {
                        Stream stream = (Stream)e.Result;
                        if (imageUrl.Contains(".gif"))
                        {
                            GifDecoder gd = new GifDecoder();
                            ImageTools.ExtendedImage image = new ImageTools.ExtendedImage();
                            gd.Decode(image, stream);
                            JpegEncoder jpeg = new JpegEncoder();
                            using (MemoryStream mstream = new MemoryStream())
                            {
                                jpeg.Encode(image, mstream);
                                bitmapimage.SetSource(mstream);
                            }
                        }
                        else
                        {
                            try
                            {
                                bitmapimage.SetSource(stream);
                            }
                            catch
                            {
                                //没有判别出图片了类型的处理
                            }
                        }
                    }
                };
                ws.OpenReadAsync(new Uri(value.ToString()), UriKind.Absolute);
            }
            return bitmapimage;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
